﻿using DataCenter.Model.Interface;
using DataCenter.Model.Model;
using Common.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataCenter.Provider
{
    public class MrpProvider : GenericProvider, IMrpProvider
    {
        public List<MRP> SearchMrp(out int totalRecord, string textSearch = null, bool? transferFlag = null, int pagesize = 0, int pageindex = 0)
        {
            var querry = repository.GetQuery<MRP>();

            if (!string.IsNullOrWhiteSpace(textSearch))
            {
                querry = querry.Where(x => x.Model.ToUpper().Contains(textSearch.ToUpper()) || x.Mrp.ToUpper().Contains(textSearch.ToUpper()));
            }

            if (transferFlag.HasValue)
            {
                string flag = transferFlag.Value.ToBooleanString();
                if (!transferFlag.Value) querry = querry.Where(x => x.SoTransferFlag.ToUpper() == flag);
                else querry = querry.Where(x => x.SoTransferFlag == null || x.SoTransferFlag.Length == 0 || x.SoTransferFlag.ToUpper() == flag);
            }

            querry = querry.OrderBy(x => x.Model).ThenBy(x => x.Mrp);
            totalRecord = querry.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                querry = querry.Skip(pageindex * pagesize).Take(pagesize);
            }
            var result = querry.ToList();
            return result;
        }


        public MRP Retrieve(string model)
        {
            if (model.IsNullOrWhiteSpace()) return null;
            return repository.FindOne<MRP>(x => x.Model.ToUpper() == model.ToUpper());
        }

        public bool Add(MRP obj)
        {
            try
            {
                repository.Mrp.Add(obj);
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool Update(MRP obj)
        {
            var updateRecord = Retrieve(obj.Model);
            try
            {
                updateRecord.Model = obj.Model;
                updateRecord.Mrp = obj.Mrp;
                updateRecord.SoTransferFlag = obj.SoTransferFlag;
                if (updateRecord.SoTransferFlag.IsYes()) updateRecord.SoTransferDate = DateTime.Now;
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
